<template>
  <div>
    <textarea :id="id" :placeholder="placeholder" class="textarea-ckeditor"></textarea>
  </div>
</template>

<script>
export default {
  name: 'ckeditor4',
  props: ['value','placeholder','height'],
  mounted: function() {
    const self = this;
    // 渲染编辑器
    self.ckeditor = window.CKEDITOR.replace(self.id,{ height: self.height, width: 'auto' });
    // 设置初始内容
    if(self.value.indexOf('</')===-1){
      self.value = `<p>${self.value}</p>`
    }
    self.ckeditor.setData(self.value);
    // 监听内容变更事件
    self.ckeditor.on('change', function() {
      self.$emit('input', self.ckeditor.getData());
    });
    self.ckeditor.on('focus', (evt) => {
      let dom = document.querySelector("#"+evt.editor.id+"_top");
      dom.style.display = "block";
      let dom1 = document.querySelector("#"+evt.editor.id+"_bottom");
      dom1.style.display = "block";
      self.$emit('input', self.ckeditor.getData());
    });
    self.ckeditor.on('blur', (evt) => {
      let dom = document.querySelector("#"+evt.editor.id+"_top");
      if (dom) {
        dom.style.display = "none";
      }
      let dom1 = document.querySelector("#"+evt.editor.id+"_bottom");
      if (dom1) {
        dom1.style.display = "none";
      }
      self.$emit('input', self.ckeditor.getData());
    });
     

    self.ckeditor.on( 'instanceReady', function( event ){
      var editor = event.editor;
      setTimeout( function(){
        // Delay bit more if editor is still not ready.
        if ( !editor.element ){
          setTimeout( arguments.callee, 100 );
          return;
        }
        event.removeListener( 'instanceReady', this.callee );
        if ( editor.name == 'content' ){
          editor.resize( editor.container.getStyle( 'width' ), CKEDITOR.document.getById( 'cke_'+'content' ).getParent().$.offsetHeight );
        }
      }, 0 );
    }, null, null, 9999 );
  }, 
  data: function() {
    return {
      id: parseInt(Math.random() * 10000).toString(),
      ckeditor: null
    };
  },
  watch: {
    // 监听prop的变化，更新ckeditor中的值
    value: function() {
      if (this.value !== this.ckeditor.getData()) {
        if(this.value.indexOf('</')===-1){
          this.value = `<p>${this.value}</p>`
        }
        this.ckeditor.setData(this.value);
      }
    }
  },
  // 销毁组件前，销毁编辑器
  // beforeDestroy: function() {
  //   self.ckeditor.destroy();
  // }
};
</script>

<style lang="scss">
.add-ti{
  .cke_top{
    display: none;
  }
  .cke_bottom{
    display: none;
  }
}
</style>